package org.marsdonne.sync;

import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory;
import org.marsdonne.sync.messenger.artemis.SyncImpl;
import org.marsdonne.sync.messenger.artemis.SyncedImplListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.annotation.EnableJms;
import org.springframework.jms.config.DefaultJmsListenerContainerFactory;
import org.springframework.jms.config.JmsListenerContainerFactory;
import org.springframework.jms.core.JmsTemplate;

import javax.jms.ConnectionFactory;

@EnableJms
@Configuration
@ConditionalOnProperty(prefix = "sync", name = {"artemis.broker-url"})
public class SyncConfigurer {

    @Value("${sync.artemis.broker-url:tcp://localhost:61616}")
    private String brokerUrl;

    @Bean
    public ConnectionFactory syncJmsConnectionFactory() {
        return new ActiveMQConnectionFactory(brokerUrl);
    }

    @Bean
    public JmsTemplate syncJmsTemplate() {
        JmsTemplate jmsTemplate = new JmsTemplate();
        jmsTemplate.setPubSubDomain(true);
        jmsTemplate.setConnectionFactory(syncJmsConnectionFactory());
        return jmsTemplate;
    }

    @Bean
    public JmsListenerContainerFactory syncedImplListenerFactory() {
        DefaultJmsListenerContainerFactory containerFactory = new DefaultJmsListenerContainerFactory();
        containerFactory.setConnectionFactory(syncJmsConnectionFactory());
        containerFactory.setPubSubDomain(true);
        return containerFactory;
    }

    @Bean
    public Syncable synchronizer() {
        return new SyncImpl();
    }

    @Bean(initMethod = "scanSyncedImpl")
    SyncedImplListener syncedByArtemis() {
        return new SyncedImplListener();
    }
}
